package com.qdsgjsfk.vision.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseActivity;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.eventbus.SocketInput;
import com.qdsgjsfk.vision.eventbus.StartVision;
import com.qdsgjsfk.vision.model.Msg;
import com.qdsgjsfk.vision.service.SocketService;
import com.qdsgjsfk.vision.util.PackageUtils;
import com.qdsgjsfk.vision.util.QrConfigUtil;
import com.qdsgjsfk.vision.util.UtilString;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
//import cn.bertsir.zbar.Qr.ScanResult;
//import cn.bertsir.zbar.QrConfig;
//import cn.bertsir.zbar.QrManager;
//import cn.bertsir.zbar.view.ScanLineView;
import cn.bertsir.zbar.Qr.ScanResult;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.QrManager;
import cn.bertsir.zbar.view.ScanLineView;
import jz.joyoung.robot.util.LogUtil;
import util.PreferencesHelper;

/**
 * Created by HP on 2019/11/29.
 */

public class IpActivity extends BaseActivity {

    @BindView(R.id.tv_ip)
    TextView tv_ip;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_cancel)
    ImageView btnCancel;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.iv_zxing)
    ImageView ivZxing;
    public int REQUEST_CODE_SCAN_IP = 5;

    @Override
    protected void initViews() {

    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        tv_ip.setText( "本机IP:" + getLocalIpAddress() );
        String TAG = "系统参数：";
        Log.e( TAG, "手机厂商：" + PackageUtils.getDeviceBrand() );
        Log.e( TAG, "手机型号：" + PackageUtils.getSystemModel() );
//        if (getWifiApState(this) == 13) {
//            Log.e( "getWifiApStateIp----", getWifiApState( this ) + "" );
//            tv_ip.setText("本机IP:192.168.43.1");
//        } else {
//            tv_ip.setText("本机IP:" + getLocalIpAddress());
//        }
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_ip;
    }

    @OnClick(R.id.btn_cancel)
    void btn_cancel() {
        GoBack();
    }

    @OnClick(R.id.btn_back)
    void btn_Back() {
        GoBack();
    }

    private void GoBack() {
        if (BaseApplication.lastActivity == 0) {
            startActivity( TypeActivity.class );
            finish();
        } else if (BaseApplication.lastActivity == 1) {
            Intent intent = new Intent( IpActivity.this, StudentDetailActivity.class );
            intent.putExtra( "studentId", BaseApplication.studentId );
            intent.putExtra( "taskId", BaseApplication.taskId );
            startActivity( intent );
            finish();
        } else if (BaseApplication.lastActivity == 2) {
            Intent intent = new Intent( IpActivity.this, StudentDetailOtherActivity.class );
            intent.putExtra( "studentId", BaseApplication.studentId );
            intent.putExtra( "taskId", BaseApplication.taskId );
            startActivity( intent );
            finish();
        }
    }

    public int getWifiApState(Context mContext) {
        WifiManager wifiManager = (WifiManager) mContext.getApplicationContext().getSystemService( Context.WIFI_SERVICE );
        try {
            Method method = null;
            if (wifiManager != null) {
                method = wifiManager.getClass().getMethod( "getWifiApState" );
            }
            assert method != null;
            return (int) (Integer) method.invoke( wifiManager );
        } catch (Exception e) {
            return -1;
        }
    }

    /**
     * 获取本地IP地址
     */
    public String getLocalIpAddress() {
        try {
            String ipv4;
            ArrayList<NetworkInterface> nilist = Collections.list( NetworkInterface.getNetworkInterfaces() );
            LogUtil.e( "nilist---" + nilist.size() );
            for (NetworkInterface ni : nilist) {
                ArrayList<InetAddress> ialist = Collections.list( ni.getInetAddresses() );
                for (InetAddress address : ialist) {
                    if (address instanceof Inet4Address) {
                        LogUtil.e( "IpAll---" + address.getHostAddress() );
                    }
                    if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                        ipv4 = address.getHostAddress();
                        return ipv4;
                    }
                }
            }

        } catch (SocketException ex) {
            Log.e( "localip", ex.toString() );
        }
        return null;
    }


    @OnClick(R.id.iv_zxing)
    public void onViewClicked() {
//        context.stopService(new Intent(context, SocketService.class));
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            context.startForegroundService(new Intent(context, SocketService.class));
//        } else {
//            context.startService(new Intent(context, SocketService.class));
//        }
        //Toast.makeText( IpActivity.this, "请扫描验光仪设备上的二维码", Toast.LENGTH_SHORT ).show();
        QrManager.getInstance().init(QrConfigUtil.getQrConfig()).startScan( this, result -> {
            Log.e( "onScanSuccess---", result.getContent() );
//                Toast.makeText( getApplicationContext(), "内容：" + result.getContent()
//                        + "  类型：" + result.getType(), Toast.LENGTH_SHORT ).show();
            if (!UtilString.isEmpty( result.getContent() )) {
                try {
                    JSONObject obj = new JSONObject( result.getContent() );
                    PreferencesHelper.getInstance().set( IpActivity.this, "ipv4", obj.optString( "ipv4" ) );
//                    Toast.makeText(this, "获取地址成功", Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().postSticky( new SocketInput( new Msg.Builder().code( 10 ).build().toString() ) );
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText( IpActivity.this, "二维码识别失败", Toast.LENGTH_SHORT ).show();
                }
            }

        } );

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        if (requestCode == REQUEST_CODE_SCAN_IP && resultCode == RESULT_OK) {
            if (data != null) {

            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        GoBack();
    }
}
